﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; 
using Utility;
using System.Data;
using Hxj.Data;
using Utility.Model;
using MsgCenter.DAL.Base;
using Utility.Helper;

namespace MsgCenter.BLL.Impl
{
    /// <summary>
    /// 部门管理业务层
    /// </summary>
    public class BLL_SysDept
    {
        private readonly BaseService dal = new BaseService();
        /// <summary>
        /// 根据父级ID找出最大的排序ID并加1，为空等于1
        /// </summary>
        /// <param name="FatherID"></param>
        /// <returns></returns>
        public int GetMaxSortByFatherID(string FatherID)
        {
            int result = 0;
            string Sql = "select max(sort)+1 from Sys_Dept where ParentID='" + FatherID + "'";
            object obj = dal.ToScalar<object>(Sql);
            if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
            {
                result = 1;
            }
            else
            {
                result = obj.ToSafeInt();
            }
            return result;
        }
        /// <summary>
        /// 根据父级ID找出最大的DeptID
        /// </summary>
        /// <param name="FatherID"></param>
        /// <returns></returns>
        public string GetMaxDeptIDByFatherID(string FatherID)
        {
            string Sql = "select max(deptid) from Sys_Dept where ParentID='" + FatherID + "'";
            object obj = dal.ToScalar<object>(Sql);
            string reult = string.Empty;
            if (obj != null)
            {
                reult = obj.ToString();
            }
            return reult.ToString();
        }
        /// <summary>
        /// 生成位数DeptID
        /// </summary>
        /// <param name="DeptId"></param>
        /// <returns></returns>
        private string GetMaxDeptIDByFather(string DeptId)
        {
            string deptid = GetMaxDeptIDByFatherID(DeptId);
            if (deptid.Length > 0)
            {
                string tmpStr = string.Empty;
                if (deptid.Length > 5)
                {
                    tmpStr = deptid.Substring(0, deptid.Length - 5);
                    deptid = deptid.Substring(deptid.Length - 5, 5);
                }
                ulong id = Convert.ToUInt64(deptid) + 1;
                switch (id.ToString().Length)
                {
                    case 1:
                        deptid = "0000" + id.ToString();
                        break;
                    case 2:
                        deptid = "000" + id.ToString();
                        break;
                    case 3:
                        deptid = "00" + id.ToString();
                        break;
                    case 4:
                        deptid = "0" + id.ToString();
                        break;
                }
                deptid = tmpStr + deptid;
            }
            else
            {
                deptid = DeptId + "00001";
            }
            return deptid;
        }
        /// <summary>
        /// 根据条件获取Table
        /// </summary>
        /// <param name="wcp">WhereClip条件</param>
        /// <returns></returns>
        public DataTable GetDeptTable(WhereClip wcp)
        {
            wcp = wcp.And(Sys_Dept._.IsDelete == false);
            return dal.GetTable<Sys_Dept>(wcp);
        }
        /// <summary>
        /// 保存修改
        /// </summary>
        /// <typeparam name="model">对象实体</typeparam>
        /// <param name="attachment"></param>
        public void Save(Sys_Dept model)
        {
            if (model.IsNewModel)
            {
                if (model.ParentID == "0")
                {
                    model.Sort = GetMaxSortByFatherID(model.ParentID);
                    model.DeptID = GetMaxDeptIDByFather(model.ParentID);
                }
                else
                {
                    Sys_Dept mdl = dal.GetModel<Sys_Dept>(new WhereClip().And(Sys_Dept._.ID == model.ParentID));
                    if (mdl != null)
                    {
                        model.ParentID = mdl.DeptID;
                        model.Sort = GetMaxSortByFatherID(mdl.DeptID);
                        model.DeptID = GetMaxDeptIDByFather(mdl.DeptID);
                    }
                    else
                    {
                        model.Sort = GetMaxSortByFatherID(model.DeptID);
                        model.DeptID = GetMaxDeptIDByFather(model.DeptID);
                    }
                }
            }
            DbTrans trans = dal.GetDataBase().BeginTransaction();
            try
            {
                dal.Save<Sys_Dept>(model, trans);
                trans.Commit();
            }
            catch (Exception ex)
            {
                trans.Rollback();
                throw ex;
            }
            finally
            {
                trans.Close();
                CacheHelper.RemoveAllCache("Sys_Dept_Tree");
            }
        }
        /// <summary>
        /// 删除,修改状态为已删除
        /// </summary>
        /// <param name="strDataID"></param>
        public void Delete(string strDataID)
        {
            string[] idList = strDataID.Trim(',').Split(',');
            DbTrans trans = dal.GetDataBase().BeginTransaction();
            try
            {
                foreach (string strID in idList)
                {
                    //dal.Delete<Sys_Dept>(Sys_Dept._.ID == id, trans);
                    dal.ExecuteNonQuery("Update Sys_dept set Isdelete=1 where ID='" + strID + "'", trans);
                }
                trans.Commit();
            }
            catch (Exception ex)
            {
                trans.Rollback();
                throw ex;
            }
            finally
            {
                trans.Close();
                CacheHelper.RemoveAllCache("Sys_Dept_Tree");
            }
        }
        /// <summary>
        /// 获取对象实体
        /// </summary>
        /// <param name="wcp"></param>
        /// <returns></returns>
        public Sys_Dept GetModel(WhereClip wcp)
        {
            return dal.GetModel<Sys_Dept>(wcp);
        }
        /// <summary>
        /// 获取对象实体
        /// </summary>
        /// <param name="wcp"></param>
        /// <returns></returns>
        public Sys_Dept GetModel(string id)
        {
            return GetModel(Sys_Dept._.ID == id);
        }
        /// <summary>
        /// 根据数组排序
        /// </summary>
        /// <param name="sz"></param>
        public void Update_Sort(string[] sz)
        {
            const string strSqlSort = " update {0} set sort={1} where ID='{2}'";
            DbTrans trans = dal.GetDataBase().BeginTransaction();
            try
            {
                for (int i = 0; i < sz.Length; i++)
                {
                    dal.ExecuteNonQuery(string.Format(strSqlSort, "Sys_Dept", i + 1, sz[i].ToString()), trans);
                }
                trans.Commit();
            }
            catch (Exception ex)
            {
                trans.Rollback();
                throw ex;
            }
            finally
            {
                trans.Close();
                CacheHelper.RemoveAllCache("Sys_Dept_Tree");
            }
        }
    }
}
